package com.cygsunri.wisdompark.callback.controller;

import com.alibaba.fastjson.JSON;
import com.cygsunri.common.TuYaConstant;
import com.cygsunri.common.YaHeConstant;
import com.cygsunri.wisdompark.util.EnumUtil;
import com.cygsunri.wisdompark.util.TuYaWebUtil;
import com.cygsunri.wisdompark.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 涂鸦平台接口调用
 * 前端控制器
 * </p>
 *
 * @author cygsunri
 * @since 2021-06-04
 */
@Slf4j
@Controller
@RequestMapping("/tuya/")
public class TuYaController {

    @Autowired
    private TuYaConstant tuyaConstant;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取令牌
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public ResponseEntity<String> token() {
        try {
            String result = TuYaWebUtil.doGet("https://openapi.tuyacn.com/v1.0/token?grant_type=1",tuyaConstant.getAccessId(),tuyaConstant.getAccessSecret(),null);
            log.info(result);
            Map<String, Object> resultMap = JSON.parseObject(result, HashMap.class);
            if((boolean)resultMap.get("success")){
                Map tempMap = (Map)resultMap.get("result");
                redisTemplate.opsForValue().set("tuyaToken",tempMap.get("access_token").toString());
            }

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage(), HttpStatus.OK);
        }
    }


    /**
     * 获取令牌
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/specifications", method = RequestMethod.GET)
    public ResponseEntity<String> specifications(String device_id) {
        try {
            String result = TuYaWebUtil.doGet("https://openapi.tuyacn.com/v1.0/devices/"+device_id+"/specifications",tuyaConstant.getAccessId(),tuyaConstant.getAccessSecret(),redisTemplate.opsForValue().get("tuyaToken").toString());
            log.info(result);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage(), HttpStatus.OK);
        }
    }
}
